package menu

import (
	"context"
	"jinrigaoping/api/platform/internal/svc"
	"jinrigaoping/api/platform/internal/types"
	"sort"

	"jinrigaoping/rpc/sys/sys"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuTreeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuTreeLogic {
	return &MenuTreeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuTreeLogic) MenuTree(req *types.SysMenuTreeReq) (resp *types.SysMenuTreeRes, err error) {

	all, err := l.svcCtx.SysRpc.SysMenuList(l.ctx, &sys.SysMenuListReq{})
	if err != nil {
		return nil, err
	}

	tree := getTreeRecursive(all.List, 0)

	sort.SliceStable(tree, func(i, j int) bool {
		return tree[i].Sort < tree[j].Sort
	})

	return &types.SysMenuTreeRes{List: tree}, nil
}
